package com.itheima.controller;

import constant.MessageConstant;
import entity.Result;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class UserController {
    
    /**
     * Spring Security在认证成功后会将用户信息保存到框架提供的上下文对象中，
     * 所以我们就可以调用Spring Security框架提供的API获取当前用户的username并展示到页面上。
     */
    @RequestMapping("/getUsername.do")
    public Result getUsername(){
        try {
            //此user是userDetails的user
            User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            return new Result(true, MessageConstant.GET_USERNAME_SUCCESS,user.getUsername());
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_USERNAME_FAIL);
        }
    }
}
